﻿using Microsoft.SharePoint.Client;
using Futajma.MigrationStudio.SharePointPersistance.Dialog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace Futajma.MigrationStudio.SharePointPersistance
{
    class ExtendedClientContext : ClientContext
    {



        public ExtendedClientContext(Uri webFullUrl) : base(webFullUrl)
        {
            //CredentialManager.Credentials = CredentialCache.DefaultNetworkCredentials;
        }
        public ExtendedClientContext(string webFullUrl) : base(webFullUrl)
        {
            //CredentialManager.Credentials = CredentialCache.DefaultNetworkCredentials;
        }

        public override void ExecuteQuery()
        {

            //.WebRequestExecutor.WebRequest.UserAgent = “Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)”; 

           // ClientContext ctx = ClaimClientContext.GetAuthenticatedContext(targetSite))

            try
            {
                base.Credentials = CredentialManager.Credentials;
                base.ExecuteQuery();
            }
            catch (WebException ex)
            {
                var resp = ex.Response as System.Net.HttpWebResponse;

                if (resp != null && resp.StatusCode == HttpStatusCode.Unauthorized)
                {
                    LoginDialog dlg = new LoginDialog();
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        CredentialManager.Credentials = new NetworkCredential(dlg.UserName, dlg.Password, dlg.Domain);
                        this.ExecuteQuery();
                    }
                    else
                    {
                        throw ex;
                    }
                }
                //else
                //{
                //    MessageBox.Show(CredentialManager.ToString());
                //}
            }
        }
    }
}
